package com.only4play.practice.common.exception;

import com.only4play.practice.common.model.RespWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;


//@RestControllerAdvice // 统一返回json数据
@ControllerAdvice // 不直接返回json数据，需要在相应方法处加上@ResponseBody
@Slf4j
public class CustomExceptionHandler {

    @Value("${spring.profiles.active}")
    private String env;
    @ExceptionHandler(value = Exception.class) // 指定捕获异常类型
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RespWrapper globalExceptionHandler(HttpServletRequest request, Exception e) {
        //如果抛出的是系统自定义的异常则直接转换
        if (e instanceof BizException) {
            log.error("异常拦截：{}", e.getMessage());
            BizException ce = (BizException) e;
            return new RespWrapper(ce.getMessage());
        } else {
            log.error("异常拦截：{} ", e.getMessage());
            String s = getTrace(e);
            if ("idc".equals(env) || "beta".equals(env)) {
                s = replaceBlank(s);
            }
            log.error("异常拦截 exception detail：{}", s);
            return new RespWrapper(-11, e.getMessage() == null ? e.toString() : e.getMessage());
        }
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.IM_USED)
    public RespWrapper innerServiceException(HttpServletRequest request, BizException e) {
        log.info("异常信息：{}", e.getMessage());
        return new RespWrapper(e.getCode(), e.getMessage());
    }


    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            dest = str.replaceAll( "\\s*|\t|\r|\n", "");
        }
        return dest;
    }

    public static String getTrace(Throwable t) {
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        t.printStackTrace(writer);
        StringBuffer buffer = stringWriter.getBuffer();
        return buffer.toString();
    }
}
